package com.ezgo.erc.master.utils;

import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * 
 * (工具)模块 TODO(支持https访问协议)
 * 
 * @author devintam
 * @date 2015年10月15日 下午4:37:28
 *
 */
public class MyX509TrustManager implements X509TrustManager {

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub

	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
		// TODO Auto-generated method stub

	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 
	 * TODO(访问https协议地址，获取返回数据结果-JSON)
	 *
	 * @param myURL
	 *            地址对象
	 * @return String
	 * @throws Exception
	 */
	public static String getRespStr(URL myURL) throws Exception {
		String jsondata = "";
		// 创建SSLContext对象，并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new MyX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		// 创建HttpsURLConnection对象，并设置其SSLSocketFactory对象
		HttpsURLConnection httpsConn = (HttpsURLConnection) myURL
				.openConnection();
		httpsConn.setSSLSocketFactory(ssf);
		// 取得该连接的输入流，以读取响应内容
		InputStreamReader insr = new InputStreamReader(
				httpsConn.getInputStream());
		// 读取服务器的响应内容并显示
		int respInt = insr.read();

		while (respInt != -1) {
			// System.out.print((char) respInt);
			jsondata = jsondata + (char) respInt;
			respInt = insr.read();
		}
		httpsConn.disconnect();
		return jsondata;
	}

}
